package com.chookss.tiku.view

import android.content.Context
import android.graphics.Color
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.View.OnFocusChangeListener
import android.view.ViewGroup
import android.widget.*
import androidx.lifecycle.MutableLiveData
import com.chookss.tools.bigImage.ImagePreview
import com.chookss.R
import com.chookss.base.StaticClass
import com.chookss.tiku.entity.Subject
import com.chookss.tiku.entity.SubjectAnswer
import com.chookss.tiku.entity.SubjectDetailEntity
import com.chookss.tiku.util.TiKuUtils
import com.chookss.tools.ClearMoreZeroUtil
import com.chookss.tools.GlideUtils
import com.chookss.tools.Utils
import com.johnrambo.ktea.ktExtends.ShareUtils
import kotlinx.android.synthetic.main.view_subject.view.*
import org.jetbrains.anko.textColor

/**
 * Company:
 * Project:
 * Author: liuhaoge
 * Date: 2020/12/29 18:31
 * Note:
 */
class SubjectView : FrameLayout {
    var enableAnswers: Boolean = true
    var myAnswersLiveData = MutableLiveData<List<String>>()
    val myAnswers = mutableListOf<String>()
    var showSubmit: Boolean = true
    var showSubjectNext: Int = 0 //0默认隐藏

    // 1隐藏下一题显示提交 无答案  做题状态
    // 2错题本展示下一题隐藏提交 有答案  选项有对号因为做题了， 练习模式下都可以用
    // 4 收藏展示下一题隐藏提交  有答案   单纯收藏下没有是否做过题的记录
    //3全部隐藏（搜索模式用）有答案
    //5背题模式，答案全是绿色的 不显示答对答错
    //6考试模式，可以来回编辑
    fun updateMyAnswers(value: List<String>?) {
        myAnswers.clear()
        value?.let { myAnswers.addAll(it) }
        updateAnswersViewState()
    }
    private fun updateAnswersViewState() {
        //查看解析的时候  更新自己答题情况
        for (i in 0 until llAnswer.childCount) {
            if (subject?.subjectTypeCode.equals("1004")) {
                var v = llAnswer.getChildAt(i)
                var edAnswer = v.findViewById<EditText>(R.id.edAnswer)
                if (myAnswers.size > i) {
                    if (myAnswers.size < i + 1) {
                        //异常
                        edAnswer.setText(myAnswers.get(myAnswers.size - 1))
                    } else {
                        edAnswer.setText(myAnswers.get(i))
                    }
                    if(showSubjectNext==6){
                        edAnswer.isEnabled = true
                    }else{
                        edAnswer.isEnabled = false
                    }
                } else {
                    myAnswers.add("")
                    edAnswer.isEnabled = true
                }


            } else if (subject?.subjectTypeCode.equals("1005")) {
                var v = llAnswer.getChildAt(i)
                var edAnswer = v.findViewById<EditText>(R.id.edAnswer)
                if (myAnswers.size > i) {
                    if (myAnswers.size < i + 1) {
                        //异常
                        edAnswer.setText(myAnswers.get(myAnswers.size - 1))
                    } else {
                        edAnswer.setText(myAnswers.get(i))
                    }
                    if(showSubjectNext==6){
                        edAnswer.isEnabled = true
                    }else{
                        edAnswer.isEnabled = false
                    }
                } else {
                    myAnswers.add("")
                    edAnswer.isEnabled = true
                }

            } else {
                var v = llAnswer.getChildAt(i)
                var tag = v.tag as SubjectAnswer
                if (showSubjectNext == 3 || showSubjectNext == 4) {
                    //答题记录和搜索模式下不展示之前答过的选项
                    v.isSelected = false
                } else {
                    v.isSelected = myAnswers.contains(tag.lvlNo)
                }
            }

        }
    }

    var answers: List<SubjectAnswer>? = null
        set(value) {
            field = value
            updateAnswersView()
        }

    var subject: Subject? = null
        set(value) {
//            if (field?.subjectCode == value?.subjectCode) {
//                return
//            }
            myAnswers.clear()
            field = value
            updateSubjectView()
            hideRightAnswerInfo()
        }

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    init {
        LayoutInflater.from(context).inflate(R.layout.view_subject, this)
    }

    private fun updateSubjectView() {
        tvTitleType.text = TiKuUtils.subjectTypeName2(subject?.subjectTypeCode ?: "")
        tvTitle.text = subject?.subjectContent ?: ""
        if ("1" == subject?.isContainPicture && !TextUtils.isEmpty(subject?.pictureUrl)) {
            ivSubject.visibility = View.VISIBLE
            GlideUtils.load(context,subject?.pictureUrl,ivSubject,R.drawable.default_banner)
        } else {
            ivSubject.visibility = View.GONE
        }
        ivSubject.setOnClickListener(OnClickListener {
            // 最简单的调用，即可实现大部分需求，如需定制，可参考下一步的自定义代码：
            ImagePreview.instance // 上下文，必须是activity，不需要担心内存泄漏，本框架已经处理好；
                .setContext(context) // 设置从第几张开始看（索引从0开始）
                .setImage(subject?.pictureUrl.toString())
                .setShowCloseButton(false)
                .setShowDownButton(false)
                .start()
        })
        tvTitleType.visibility = View.VISIBLE
        if (showSubjectNext == 1) {
            enableAnswers = true
            tvSubmit.visibility = View.VISIBLE
            tvSubjectNext.visibility = View.GONE
        } else if (showSubjectNext == 2 || showSubjectNext == 4) {
            tvSubmit.visibility = View.GONE
            tvSubjectNext.visibility = View.VISIBLE
            enableAnswers = false
        } else if (showSubjectNext == 3) {
            tvSubmit.visibility = View.GONE
            tvSubjectNext.visibility = View.GONE
            enableAnswers = false
        } else {
            if (showSubmit) {
                tvSubmit.visibility = View.VISIBLE
                enableAnswers = true
            } else {
                tvSubmit.visibility = View.GONE
                enableAnswers = true
            }
            tvSubjectNext.visibility = View.GONE
        }


    }

    fun hiddeAnswerDetail() {
        myAnswers.clear()
        updateSubjectView()
        updateAnswersView()
        hideRightAnswerInfo()
    }

    private val abcde = "ABCDEFGHIJK"

    fun showRightAnswerInfo(answerIsTrue: Boolean = false) {
        var rightAbcde = ""

        llRightAnswer.visibility = View.VISIBLE
        if (showSubjectNext == 0 || showSubjectNext == 1 || showSubjectNext == 2) {
            if (answerIsTrue) {
                tvWrong.text = "回答正确"
            } else {
                if (subject?.subjectTypeCode.equals("1004") || subject?.subjectTypeCode.equals("1005")) {
                    tvWrong.text = if (subject?.isRight.equals("1")) "回答正确" else "回答错误"
                } else {
                    tvWrong.text =
                        if (TiKuUtils.myAnswerIsRight(answers, myAnswers)) "回答正确" else "回答错误"
                }

            }
            if (tvWrong.text.toString().equals("回答正确")) {
                tvWrong.textColor = Color.parseColor("#08D2A5")
            } else {
                tvWrong.textColor = Color.parseColor("#F2434D")
            }
            tvWrong.visibility = View.VISIBLE
        } else {
            tvWrong.visibility = View.GONE
        }
        answers?.forEachIndexed { index, subjectAnswer ->
            if (subject?.subjectTypeCode.equals("1004")) {
                if (rightAbcde.length > 0) {
                    rightAbcde += "、"
                }
                rightAbcde += subjectAnswer.answerContent
                setBackground(index, subjectAnswer)
            } else if (subject?.subjectTypeCode.equals("1005")) {
                rightAbcde = subjectAnswer.answerContent
                setBackground(index, subjectAnswer)
            } else {
                var v = llAnswer.getChildAt(index)
                var tag = v.tag as SubjectAnswer
                if (subjectAnswer.isRightAnswer == "1") {
                    if (rightAbcde.length > 0) {
                        rightAbcde += ", "
                    }
                    rightAbcde += abcde[index]
                    if (showSubjectNext == 0 || showSubjectNext == 1 || showSubjectNext == 2) {
                        if (tvWrong.text.toString().equals("回答正确")) {
                            v.background =
                                context?.resources?.getDrawable(R.drawable.shape_37d0ae_4)
                        } else {
                            v.background =
                                context?.resources?.getDrawable(R.drawable.shape_e43d1c_4)
                        }
                    } else {
                        //背题模式  或者搜索结果页时候
                        v.background = context?.resources?.getDrawable(R.drawable.shape_37d0ae_4)
                    }

                } else {
                    v.background = context?.resources?.getDrawable(R.drawable.shape_f7f7f7_4)
                }
            }
        }
        tvRightAnswer.text = rightAbcde
        GlideUtils.loadAvatar(
            context,
            ShareUtils().getString(context, StaticClass.USER_AVATAR_URL, ""),
            ivHead
        )
    }

    fun setBackground(index: Int, subjectAnswer: SubjectAnswer) {
        //简单题和填空题 item及答案绘制
        if (subject?.subjectTypeCode.equals("1004")) {
            var v = llAnswer.getChildAt(index)
            var llBg = v.findViewById<LinearLayout>(R.id.llBg)
            var edAnswer = v.findViewById<EditText>(R.id.edAnswer)
            edAnswer.isEnabled = false
            var tag = llBg.tag as SubjectAnswer
            if (showSubjectNext == 0 || showSubjectNext == 1 || showSubjectNext == 2) {
                if (subject?.isRight == "1") {
                    llBg.background = context?.resources?.getDrawable(R.drawable.shape_37d0ae_4)
                } else {
                    llBg.background = context?.resources?.getDrawable(R.drawable.shape_e43d1c_4)
                }
            } else {
                //背题模式  或者搜索结果页时候
                llBg.background = context?.resources?.getDrawable(R.drawable.shape_37d0ae_4)
            }
        } else {
            var v = llAnswer.getChildAt(index)
            var edAnswer = v.findViewById<EditText>(R.id.edAnswer)
            edAnswer.isEnabled = false
            var tag = v.tag as SubjectAnswer
            if (showSubjectNext == 0 || showSubjectNext == 1 || showSubjectNext == 2) {
                if (subject?.isRight == "1") {
                    v.background = context?.resources?.getDrawable(R.drawable.shape_37d0ae_4)
                } else {
                    v.background = context?.resources?.getDrawable(R.drawable.shape_e43d1c_4)
                }
            } else {
                //背题模式  或者搜索结果页时候
                v.background = context?.resources?.getDrawable(R.drawable.shape_37d0ae_4)
            }
        }

    }

    fun showAnswerDetail(subjectDetailEntity: SubjectDetailEntity) {
        enableAnswers = false
        if (showSubjectNext == 1 || showSubjectNext == 2 || showSubjectNext == 4 || showSubjectNext == 5) {
            tvSubjectNext.visibility = View.VISIBLE
            tvSubmit.visibility = View.GONE
        } else {
            tvSubmit.visibility = View.GONE
            tvSubjectNext.visibility = View.GONE
        }

        llRightAnswer.visibility = View.VISIBLE
        if (subject?.subjectTypeCode.equals("1005")) {
            if (Utils.isNull(subjectDetailEntity.score)) {
                llScore.visibility = View.GONE
            } else {
                llScore.visibility = View.VISIBLE
                tvScorePoint.text = subjectDetailEntity.score
            }
        } else {
            llScore.visibility = View.GONE
        }
        if (subject?.subjectTypeCode.equals("1004") || subject?.subjectTypeCode.equals("1005")) {
            //不显示易错项
            llEasyWrong.visibility = View.GONE
        } else {
            llEasyWrong.visibility = View.VISIBLE
        }
        ratingBarSubject.numStars = 5
        if (Utils.isNull(subjectDetailEntity.hardLvl)) {
            ratingBarSubject.rating = 0f
        } else {
            ratingBarSubject.rating = subjectDetailEntity.hardLvl.toFloat()
        }
        tvPersonal.text =
            "个人统计：作答本题" + (Utils.changeNumber(subjectDetailEntity.rightNum) + Utils.changeNumber(
                subjectDetailEntity.errorNum
            )) + "次" + ",做错" + Utils.changeNumber(subjectDetailEntity.errorNum) + "次"
        tvAllAnswerNum.text = Utils.changeNumber(subjectDetailEntity.allAnswerNum).toString() + ""
        tvAllRatio.text = ClearMoreZeroUtil.subZeroAndDot(subjectDetailEntity.allRightRatio) + ""
        tvEasWrong.text = TiKuUtils.errorAnswer(subjectDetailEntity.errorProneOption)
        tvCurve.text = TiKuUtils.subjecMemoryLv(subjectDetailEntity.memoryLvl)
        if (tvCurve.text.toString().contains("未记忆")) {
            tvCurve.textColor = Color.parseColor("#FFB228")
        } else if (tvCurve.text.toString().contains("开始记忆") || tvCurve.text.toString()
                .contains("正在巩固")
        ) {
            tvCurve.textColor = Color.parseColor("#08D2A5")
        } else if (tvCurve.text.toString().contains("已牢记")) {
            tvCurve.textColor = Color.parseColor("#11B3FF")
        } else {
            tvCurve.textColor = Color.parseColor("#FF5B0B")
        }
        if (Utils.isNull(subject?.answerDetail)) {
            tvRightInfo.visibility = View.GONE
            tvRightInfoInit.visibility = View.GONE
        } else {
            var answer: String = subject?.answerDetail?.replace(" ", "").toString();
            if (answer.length > 0) {
                tvRightInfo.text = subject?.answerDetail
                tvRightInfo.visibility = View.VISIBLE
                tvRightInfoInit.visibility = View.VISIBLE
            } else {
                tvRightInfo.visibility = View.GONE
                tvRightInfoInit.visibility = View.GONE
            }

        }
        if (Utils.isNull(subjectDetailEntity.keyWord)) {
            tvKeywords.visibility = View.GONE
            tvKeywordsInit.visibility = View.GONE
        } else {
            tvKeywords.text = subjectDetailEntity.keyWord
            tvKeywords.visibility = View.VISIBLE
            tvKeywordsInit.visibility = View.VISIBLE
        }
        if (Utils.isNull(subjectDetailEntity.provideEmployeeName)) {
            tvProvider.visibility = View.GONE
            tvProviderInit.visibility = View.GONE
        } else {
            tvProvider.text = subjectDetailEntity.provideEmployeeName
            tvProvider.visibility = View.VISIBLE
            tvProviderInit.visibility = View.VISIBLE
        }
    }

    private fun hideRightAnswerInfo() {
        llRightAnswer.visibility = View.GONE
    }

    private fun updateAnswersView() {
        llAnswer.removeAllViews()
        answers?.forEachIndexed { index, answer ->
            if (subject?.subjectTypeCode.equals("1004")) {
                createFillBlanksAnswerView(llAnswer, answer, index)
            } else if (subject?.subjectTypeCode.equals("1005")) {
                createShortAnswerView(llAnswer, answer, index)
            } else {
                createAnswerView(llAnswer, answer, index)
            }

        }
    }


    //创建答案视图  单选多选判断
    private fun createAnswerView(parent: ViewGroup, answer: SubjectAnswer, index: Int) {
        LayoutInflater.from(context).inflate(R.layout.item_answer, parent)
        var view = parent.getChildAt(parent.childCount - 1)
        view.findViewById<TextView>(R.id.tvAnswer).text = abcde[index] + "  " + answer.answerContent
        if (showSubjectNext == 3 || showSubjectNext == 4) {
            //答题记录和搜索模式下不展示之前答过的选项
            view.isSelected = false
        } else {
            view.isSelected = myAnswers.contains(answer.lvlNo)
        }
        var ivAnswer = view.findViewById<ImageView>(R.id.ivAnswer)
        if ("1" == answer?.isContainPicture && !TextUtils.isEmpty(answer?.pictureUrl)) {
            ivAnswer.visibility = View.VISIBLE
            GlideUtils.load(context,answer?.pictureUrl,ivAnswer,R.drawable.default_banner)
         } else {
            ivAnswer.visibility = View.GONE
        }
        ivAnswer.setOnClickListener(OnClickListener {
            // 最简单的调用，即可实现大部分需求，如需定制，可参考下一步的自定义代码：
            ImagePreview
                .instance // 上下文，必须是activity，不需要担心内存泄漏，本框架已经处理好；
                .setContext(context) // 设置从第几张开始看（索引从0开始）
                .setImage(answer?.pictureUrl.toString())
                .setShowCloseButton(false)
                .setShowDownButton(false)
                .start()
        })

        view.tag = answer
        view.isEnabled = enableAnswers
        if (enableAnswers) {
            view.setOnClickListener {
                if (!enableAnswers) {
                    return@setOnClickListener
                }
                if (myAnswers.contains(answer.lvlNo)) {
                    it.isSelected = false
                    myAnswers.remove(answer.lvlNo)
                } else {
                    it.isSelected = true
                    myAnswers.add(answer.lvlNo)
                }
                if (subject?.subjectTypeCode != "1002") {//非多选模式 反选其他
                    unselectedAllBut(it)
                    myAnswersLiveData.postValue(ArrayList(myAnswers))
                } else {
                    myAnswersLiveData.postValue(ArrayList(myAnswers))
                }
            }
        }
    }

    //创建答案视图  填空
    private fun createFillBlanksAnswerView(parent: ViewGroup, answer: SubjectAnswer, index: Int) {
        LayoutInflater.from(context).inflate(R.layout.item_answer_fill_blank, parent)
        var view = parent.getChildAt(parent.childCount - 1)
        view.findViewById<TextView>(R.id.tvAnswerInit).text = "填空" + (index + 1)
        var edAnswer = view.findViewById<EditText>(R.id.edAnswer)
        edAnswer.isEnabled = true
        var llBg = view.findViewById<LinearLayout>(R.id.llBg)

        if (showSubjectNext == 3 || showSubjectNext == 4) {
            //答题记录和搜索模式下不展示之前答过的选项
            edAnswer.setText(answer.answerContent)
        }
        myAnswers.add("")
        edAnswer.setOnFocusChangeListener(OnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                // 此处为得到焦点时的处理内容
                llBg.background = context?.resources?.getDrawable(R.drawable.shape_f8f8fa_03b8f3_4)
            } else {
                // 此处为失去焦点时的处理内容
                llBg.background = context?.resources?.getDrawable(R.drawable.shape_f8f8fa_4)
            }
        })
        edAnswer.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable) {

                if (myAnswers.size > index) {
                    if (myAnswers.size < index + 1) {
                        //异常
                        myAnswers.set(myAnswers.size - 1, s.toString());
                    } else {
                        myAnswers.set(index, s.toString());
                    }
                    myAnswersLiveData.postValue(ArrayList(myAnswers))
                }
            }
        })
        llBg.tag = answer
        view.isEnabled = enableAnswers
    }

    //创建答案视图  简答
    private fun createShortAnswerView(parent: ViewGroup, answer: SubjectAnswer, index: Int) {
        LayoutInflater.from(context).inflate(R.layout.item_short_answer, parent)
        var view = parent.getChildAt(parent.childCount - 1)
        var edAnswer = view.findViewById<EditText>(R.id.edAnswer)
        if (showSubjectNext == 3 || showSubjectNext == 4) {
            //答题记录和搜索模式下不展示之前答过的选项
            edAnswer.setText(answer.answerContent)
        }
        edAnswer.isEnabled = true
        var llBg = view.findViewById<LinearLayout>(R.id.llBg)
        myAnswers.add("")
        edAnswer.setOnFocusChangeListener(OnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                // 此处为得到焦点时的处理内容
                llBg.background = context?.resources?.getDrawable(R.drawable.shape_f8f8fa_03b8f3_4)
            } else {
                // 此处为失去焦点时的处理内容
                llBg.background = context?.resources?.getDrawable(R.drawable.shape_f8f8fa_4)
            }
        })
        edAnswer.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable) {
                myAnswers.set(0, s.toString());
                myAnswersLiveData.postValue(ArrayList(myAnswers))
            }
        })
        llBg.tag = answer
    }

    //反选所有非 view 答案视图
    private fun unselectedAllBut(view: View) {
        for (i in 0 until llAnswer.childCount) {
            var v = llAnswer.getChildAt(i)
            if (v.isSelected && v != view) {
                v.isSelected = false
                var tag = v.tag as SubjectAnswer
                myAnswers.remove(tag.lvlNo)
            }
        }
    }

}